from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from books.models import HeroInfo
from heros.serialziers import HeroSerializer
# 导入认证方式
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
# 导入权限
from rest_framework.permissions import IsAuthenticated
# 导入限流用户
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
# 导入排序方法类
from rest_framework.filters import OrderingFilter
# 导入自定义分页器
from heros.utils import NumPage
from django_filters.rest_framework import DjangoFilterBackend
class HerosView(ModelViewSet):
    # 查询集
    queryset = HeroInfo.objects.all()
    # 序列化器
    serializer_class = HeroSerializer
    # 认证属性配置
    authentication_classes = [BasicAuthentication, SessionAuthentication]
    # 权限属性配置
    permission_classes = [IsAuthenticated]
    # 限流属性配置 指定限流的用户
    # throttle_classes = [AnonRateThrottle, UserRateThrottle]
    # 按照视图限流  指定视图的限流名称
    # throttle_scope = 'heros'
    # 指定过滤字段

    # 指定排序方法
    filter_backends = [OrderingFilter,DjangoFilterBackend]
    filter_fields = ('hname', 'hgender')
    # 指定排序字段
    ordering_fields = ['id']
    # 指定分页器
    pagination_class = NumPage

    @action(methods=['get'],
            detail=True)  # 使用该装饰器对自定义的方法生成路由 methods指定请求方式  detail指定是否需要生成pk值的正则匹配 detail=False表示不需要生成正则匹配
    def last_data(self, request, pk):
        """
            获取最后一个英雄数据
        :param request:
        :return:
        """
        # 制造异常
        a = 1/0
        hero = HeroInfo.objects.latest('id')
        ser = self.get_serializer(hero)
        return Response(ser.data)
